package it.thalaz.filter.admin;

import it.thalaz.dataaccess.dto.Utenti;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import javax.servlet.http.HttpSession;

public class LoginFilter
implements Filter
{
	public void destroy()
	{
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
	{
		HttpServletRequest req = new HttpServletRequestWrapper((HttpServletRequest)request);
		HttpServletResponse res = new HttpServletResponseWrapper((HttpServletResponse)response);
		String uri = req.getRequestURI();
		HttpSession session = req.getSession();
		Utenti user = (Utenti)session.getAttribute("user");
		if ((uri != null) && (!uri.endsWith("login.jsp")) && (!uri.endsWith("logout.jsp")) && (user == null))
		{
			res.sendError(401, "Sessione NON valida: riautenticarsi.");
			return;
		}
		chain.doFilter(request, response);
	}

	public void init(FilterConfig filterConfig)
	throws ServletException
	{
	}
}

//trottole